package com.matrix.framework.audit.repositories;

import com.matrix.framework.audit.data.AuditLogPo;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 审计日志仓库
 *
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2024/10/3 11:15
 * @Since 1.0
 */
@Repository
public interface AuditLogRepository extends R2dbcRepository<AuditLogPo, Long> {

    @Query("SELECT * FROM audit_log WHERE true " +
            "AND (:search IS NULL OR :search = '' OR " +
            "username LIKE CONCAT('%', :search, '%') OR " +
            "module LIKE CONCAT('%', :search, '%') OR " +
            "action LIKE CONCAT('%', :search, '%') OR " +
            "details LIKE CONCAT('%', :search, '%')) " +
            "ORDER BY timestamp DESC LIMIT :limit OFFSET :offset")
    Flux<AuditLogPo> findAllWithSearch(String search, int limit, long offset);

    @Query("SELECT COUNT(*) FROM audit_log WHERE true " +
            "AND (:search IS NULL OR :search = '' OR " +
            "username LIKE CONCAT('%', :search, '%') OR " +
            "module LIKE CONCAT('%', :search, '%') OR " +
            "action LIKE CONCAT('%', :search, '%') OR " +
            "details LIKE CONCAT('%', :search, '%'))")
    Mono<Long> countWithSearch(String search);

    @Query("SELECT * FROM audit_log ORDER BY timestamp DESC LIMIT :limit OFFSET :offset")
    Flux<AuditLogPo> findAllWithPagination(int limit, long offset);

    @Query("SELECT COUNT(*) FROM audit_log")
    Mono<Long> countAll();
} 